﻿using Microsoft.AspNetCore.Authorization;

namespace SecretDemo
{
    //1.创建自定义授权要求类
    public class ValidUserRequirement:IAuthorizationRequirement
    {
        public string ActionCode { get;}
        public ValidUserRequirement(string? actionCode=null)
        {
            this.ActionCode = actionCode;
        }
    }
    //2.创建自定义授权处理器
    public class  ValidUserAuthorizationHandler:AuthorizationHandler<ValidUserRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidUserRequirement requirement)
        {
            //检查用户是否认证
            if (!context.User.Identity.IsAuthenticated) { 
                context.Fail();//403
                return Task.CompletedTask;
            }
            //根据自定义业务验证用户的有效期
            string account = context. User.Identity.Name;
            //读取数据库的user
            var userDB = new UserDBAccess().GetUser(account);
            if (userDB == null||userDB.Status==0)
            {
                context.Fail();//403
                return Task.CompletedTask;
            }
            //用户角色，功能权限，
            if(!string.IsNullOrEmpty(requirement.ActionCode)
                && !userDB.ActionCodeList.Contains(requirement.ActionCode))
            {
                context.Fail();//403
                return Task.CompletedTask;
            }

                context.Succeed(requirement);
            return Task.CompletedTask;

        }
    }
}
